<template>
  <div v-if="visible" class="show-modal">
    <div class="show-modal-title flex">{{ config.title }}</div>
    <div class="show-modal-content flex">{{ config.content }}</div>
    <div class="flex">
      <div
        v-if="config.showCancel"
        class="show-modal-btn flex-1 flex"
        :style="cancelStyle"
        @click="handleCancel"
      >
        {{ config.cancelText }}
      </div>
      <div class="show-modal-btn flex-1 flex" :style="confirmStyle" @click="handleConfirm">
        {{ config.confirmText }}
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import type { ModalData } from '@/types'
import { computed, ref } from 'vue'
let promiseResolve: (value: string | PromiseLike<string>) => void = () => {}
const props = defineProps({
  unmount: {
    type: Function,
    default: () => {},
  },
})

const visible = ref(false)
const baseConfig = ref<Partial<ModalData>>({
  title: '提示',
  content: '',
  showCancel: false,
  confirmText: '确定',
  cancelText: '取消',
  confirmColor: '#ff5000',
})
const config = ref<ModalData>({} as ModalData)
const confirmStyle = computed(() => {
  return `color: ${config.value.confirmColor}`
})
const cancelStyle = computed(() => {
  return `color: ${config.value.cancelColor}`
})
const asyncShowModal = async (cfg: ModalData): Promise<string> => {
  visible.value = true
  config.value = Object.assign(config.value, baseConfig.value, cfg)
  return new Promise((resolve) => {
    promiseResolve = resolve
  })
}
const handleConfirm = () => {
  visible.value = false
  props.unmount()
  promiseResolve('confirm')
  if (typeof config.value.confirm === 'function') {
    config.value.confirm()
  }
}
const handleCancel = () => {
  visible.value = false
  props.unmount()
  promiseResolve('cancel')
  if (typeof config.value.cancel === 'function') {
    config.value.cancel()
  }
}
defineExpose({
  asyncShowModal,
})
</script>
<style lang="scss" scoped>
.show-modal {
  position: fixed;
  z-index: 999;
  top: 20%;
  left: 50%;
  width: 300px;
  margin-left: -150px;
  padding: 15px 30px;
  border-radius: 8px;
  box-shadow: 0 4px 16px #00000026;
  background: #fff;
}
.show-modal-title {
  font-size: 16px;
  font-weight: 500;
}
.show-modal-content {
  padding: 20px 0;
}
.show-modal-content {
}
</style>
